#encoding=utf-8
from math import sqrt
import shelve

db = dict()
predb = dict()
	
compare_file = open("compare_score.txt",'w')

#def Corr(u,w):
	


def cal_score(userid,movieid,real_score):
	global db, predb,compare_file
	if db.has_key( userid ):
		count = 0
		sum = 0
		down_sum = 0
		up_sum = 0
		my_mean = predb[ str( userid ) ][ 'user_mean' ]
		for neighbor_list in db[ userid ]:
			neighbor, sim = neighbor_list
			for mov_id in predb[ str( neighbor ) ]:
				if mov_id == movieid:
					neighbor_score = float( predb[ str( neighbor ) ][ mov_id ][ 'score' ] )
					neighbor_mean = predb[ str( neighbor ) ][ 'user_mean' ]
					up_sum += ( neighbor_score - neighbor_mean ) * sim
					down_sum += abs ( sim )
					
					count += 1
					break
			#if count > 5:	break#break
				
		if count == 0 or down_sum == 0:
			return 4
		#print	up_sum / down_sum + predb[ str( userid ) ][ 'user_mean' ]
		pre_score = up_sum / down_sum + predb[ str( userid ) ][ 'user_mean' ]
		if pre_score > 4.75 : pre_score = 5.0
		elif pre_score > 4.25: pre_score = 4.5
		elif pre_score > 3.75: pre_score = 4.0
		elif pre_score > 3.25: pre_score = 3.5
		elif pre_score > 2.75: pre_score = 3.0
		
		elif pre_score > 2.25: pre_score = 2.5
		elif pre_score > 1.75: pre_score = 2.5
		elif pre_score > 1.25: pre_score = 2.0
		elif pre_score > 0.75: pre_score = 2.0
		else : 	pre_score = 1.0
		
		if abs ( pre_score - float(real_score) ) > 1:
			compare_file.write(str(pre_score) + '\t' + str( real_score ) +'\n')			
		return 	pre_score
		
	else:
		return 4

db2 = shelve.open( 'neighbour.db' )
for k in db2:
	db[ k ] = db2[ k ]
predb2 = shelve.open( 'data.db' )
for k in predb2:
	predb[ k ] = predb2[ k ]

f = open( "testSetTemp.txt" )
mae_sum = 0
rmse_sum = 0
i = 0
for line in ( l.split("::") for l in f ):
	userid = line[ 0 ]
	movieid = line[ 1 ]
	real_score = line[ 4 ].strip()
	mae_sum += abs ( cal_score(userid,movieid,real_score) - float(real_score) )
	rmse_sum += pow( cal_score(userid,movieid,real_score) - float(real_score),2)
	print '.',
	i += 1
MAE = mae_sum /i
RMSE = sqrt (rmse_sum/i)
print MAE
print RMSE
f.close()

	
	
